package com.sgb.member;

import static com.swgk.core.base.model.factory.BaseUrlInterceptor.HEADERS_URL;
import static com.swgk.core.base.model.factory.BaseUrlInterceptor.HEADERS_URL_MEMBER;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import com.alibaba.android.arouter.facade.template.IProvider;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.sgb.member.entity.MaterialFilterJson;
import com.sgb.member.service.MemberAPI;
import com.sgb.member.weight.MRoundCornerDialog;
import com.swgk.core.base.api.AppFolwLogApi;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.base.aroute.SimpleARouteCallback;
import com.swgk.core.base.aroute.provider.MerchandiseProvider;
import com.swgk.core.base.aroute.provider.OtherProvider;
import com.swgk.core.base.aroute.provider.PickBiddingProvider;
import com.swgk.core.base.aroute.provider.WebViewProvider;
import com.swgk.core.base.api.APIManager;
import com.swgk.core.util.MLog;
import com.swgk.core.util.SharedPreferenceUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class MemberConfig {

    public static final int REQ_SERVICE = 5001;
    public static final int REQ_MEMBER_TYPE = 5002;
    public static final int REQ_INDUSTRY_TYPE = 5003;
    public static final int REQ_MANAGEMENT_TYPE = 5004;
    public static final int REQ_SERVICE_TYPE = 5005;
    public static final int REQ_MAP = 5006;
    public static final int REQ_FILE_CHOOSE = 5007;
    public static final String JUMP_RECORD = "EXTRA_JUMP_RECORD";
    public static final String JUMP_RECORD_APPROVAL = "EXTRA_JUMP_APPROVAL_RECORD";
    public static final String EXTRA_ENTITY = "EXTRA_ENTITY";

    public static final int WEBSITE_FOR_COMPANY = 1;//企业网站
    public static final int WEBSITE_FOR_TEAM = 2;//团队网站
    public static final int WEBSITE_FOR_PERSONAL = 0; //个人网站

    public static final String BASE_URL_RELEASE = "http://gateway.shigongbang.com/sgb-app-android/";
    public static final String BASE_URL_RELEASE_Member = "http://gateway.shigongbang.com/zjkj-app-android/";
    public static final String BASE_URL_PRE = "https://api.jingyingbang.net/sgb-app/";
    public static final String BASE_URL_PRE_Member = "http://api.jingyingbang.net/zjkj-app/";
    public static final String BASE_URL_DEBUG = "http://api.sgbwl.com/sgb-app/";
    public static final String BASE_URL_DEBUG_Member = "http://api.sgbwl.com/zjkj-app/";
    /**
     * Route 配置
     */
    public static final String ROUTE_MAIN = "/member/main"; //  MemberMainActivity == 首页
    public static final String ROUTE_MAIN_2 = "/member/main2"; //  MemberMainActivity == 首页
    public static final String ROUTE_MAIN_FRAGMENT = "/member/mainFragment"; // HomeMemberFragment -- 首页的Fragment
    public static final String ROUTE_INVITE_APPLY = AppRouteConstant.MemberInviteOrApplyActivity; // MemberInviteOrApplyActivity --邀请会员、申请会员

    private static MemberConfig instance;
    private static String baseUrl;
    private static String baseUrl_Member;
    private final Map<Class<? extends IProvider>, IProvider> iProviders;
    private MemberAPI api;
    private AppFolwLogApi appFolwLogApi;
    private APIManager apiManger;


    public static MemberConfig getInstance() {
        if (instance == null) {
            synchronized (MemberConfig.class) {
                if (instance == null) {
                    instance = new MemberConfig();
                }
            }
        }
        return instance;
    }

    /**
     * 会员模块初始化网络
     * @param context
     * @param buildType 根据这个的值来选用域名环境
     *                  pre 预发环境
     *                  debug 测试环境
     *                  release 正式环境
     */
    public static void init(Context context, String buildType) {
        SharedPreferenceUtil.init(context);
        initBaseUrl(buildType);
        getInstance().changeApi();
    }

    /**
     * 初始化网络访问域名
     * @param buildType
     */
    private static void initBaseUrl(String buildType){
        if ("release".equals(buildType)) {
            baseUrl = MemberConfig.BASE_URL_RELEASE;
            baseUrl_Member = MemberConfig.BASE_URL_RELEASE_Member;
            MLog.isOnlin = true;
        } else if ("pre".equals(buildType)) {
            baseUrl = MemberConfig.BASE_URL_PRE;
            baseUrl_Member = MemberConfig.BASE_URL_PRE_Member;
            MLog.isOnlin = false;
        } else if ("debug".equals(buildType)) {
            baseUrl = MemberConfig.BASE_URL_DEBUG;
            baseUrl_Member = MemberConfig.BASE_URL_DEBUG_Member;
            MLog.isOnlin = false;
        }
        MLog.e("会员初始化环境域名：" + MLog.DEBUG_LOG ,buildType + " : " + baseUrl);
    }

    private MemberConfig() {
        iProviders = new HashMap<>();
    }

    public <T extends IProvider> T getProvider(Class<T> service) {
        T navigation = (T) iProviders.get(service);
        if (navigation == null) {
            navigation = ARouter.getInstance().navigation(service);
            iProviders.put(service, navigation);
        }
        return navigation;
    }

    public MemberAPI getApi() {
        if (api == null) {
            api = changeApi();
        }
        return api;
    }

    private MemberAPI changeApi() {
        if (apiManger == null){
            if (TextUtils.isEmpty(baseUrl)){
                initBaseUrl(BuildConfig.BUILD_TYPE);
            }
            apiManger = APIManager.getInstance(baseUrl);
        }
        apiManger.addInterceptor(getInterceptor());
        api = apiManger.create(MemberAPI.class);
        MLog.e("会员初始化使用域名：" + MLog.DEBUG_LOG , " 当前环境 " + getType() +" : " + baseUrl);
        return api;
    }

    private Interceptor getInterceptor(){
        return chain -> {
            Request request = chain.request();
            Request.Builder builder = request.newBuilder();
            Request.Builder requestBuilder = getMemberRequestBuilder(request, builder);
            MLog.e("会员使用域名：" + MLog.DEBUG_LOG,getType() + ":" + request.url().toString());
            if (requestBuilder != null) {
                return chain.proceed(requestBuilder.build());
            } else {
                return chain.proceed(request);
            }
        };
    }

    private Request.Builder getMemberRequestBuilder(Request request, Request.Builder builder) {
        String[] urlMember = HEADERS_URL.split(":");
        List<String> urlHeaders = request.headers(urlMember[0]);
        if (urlHeaders.size() > 0) {
            String oldUrl = request.url().toString();
            for (String urlHeader : urlHeaders) {
                if (urlHeader.equals(HEADERS_URL_MEMBER.split(":")[1])) {
                    builder.url(oldUrl.replace(baseUrl, baseUrl_Member));
                }
            }
            return builder;
        }
        return null;
    }

    public AppFolwLogApi AppFolwLogApi() {
        if (apiManger == null){
            apiManger = APIManager.getInstance(baseUrl);
        }
        appFolwLogApi = apiManger.create(AppFolwLogApi.class);
        return appFolwLogApi;
    }

    private String getType(){
        String type = "debug";
        if (baseUrl.equals(MemberConfig.BASE_URL_RELEASE)) {
            type = "release";
        } else if (baseUrl.equals(MemberConfig.BASE_URL_PRE)) {
            type = "pre";
        } else if (baseUrl.equals(MemberConfig.BASE_URL_DEBUG)) {
            type = "debug";
        }
        return type;
    }



/*    public void setComType(int comType) {
        this.comType = comType;
        if (comType < 0) {
            this.comType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        }
    }*/

    private int comType;// 类型 0个人 1企业 2团队

    public int getComType() {
        return SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
    }

    /**
     * 登录身份是否是企业
     *
     * @return true：是  false：否
     */
    public boolean isCompany() {
        //0个人 1企业 2团队
        int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        return type == 1;
    }

    /**
     * 登录身份是否是团队
     *
     * @return true：是  false：否
     */
    public boolean isTeam() {
        //0个人 1企业 2团队
        int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        return type == 2;
    }

    /**
     * 登录身份是否是个人
     *
     * @return true：是  false：否
     */
    public boolean isPersonal() {
        //0个人 1企业 2团队
        int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        return type == 0;
    }

    public boolean isPermission() {
        return SharedPreferenceUtil.getInstance()
                .getSaveStringData(SharedPreferenceUtil.IS_DATA, "")
                .contains("会员成员");
    }

    public boolean isHavePermission(String name) {
        return SharedPreferenceUtil.getInstance()
                .getSaveStringData(SharedPreferenceUtil.PERMISSION_HUI_YUAN, "")
                .contains(name);
    }


    public void showACDialog(Context context) {
        String confirm = "确定";
        String content = "该账户无权限，请联系企业管理员";
        View view = View.inflate(context, R.layout.dialog_two_btn, null);
        final MRoundCornerDialog roundCornerDialog = new MRoundCornerDialog(context, 0, 0, view, R.style.MRoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失

        TextView tv_confirm = (TextView) view.findViewById(R.id.tv_logout_confirm);
        TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
        TextView tv_title = view.findViewById(R.id.tv_title);
        tv_title.setVisibility(View.VISIBLE);
        TextView tv_logout_cancel = (TextView) view.findViewById(R.id.tv_logout_cancel);
        tv_title.setText("温馨提示");
        tv_confirm.setText(confirm);
        tv_message.setText(content);
        //确定
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    // 跳转企业地图

    /**
     * PickCompanyLocationMapActivity.start(getContext(), headerBean.longitude,
     * headerBean.latitude,
     * headerBean.businessAddress,
     * headerBean.companyName);
     */
    public void companyLocationMap(Context context, String lon, String lat, String address, String comName) {
        PickBiddingProvider navigation = getProvider(PickBiddingProvider.class);
        if (navigation != null) {
            navigation.startPickCompanyLocationMapActivity(context, lon, lat, address, comName);
        }
    }

    /**
     * TenderDetailsActivity3.start(getActivity(), bean.getNo(), 0);
     */
    public void startTenderDetails(Context context, String no, int type) {
        PickBiddingProvider navigation = getProvider(PickBiddingProvider.class);
        if (navigation != null) {
            navigation.startTenderDetailsActivity3(context, no, type);
        }
    }

    /**
     * PickNoticeDetailActivity.start(getActivity(), preNoticeItemEntity.getTenderNo() + "");
     */
    public void startPickNoticeDetail(Context context, String no) {
        PickBiddingProvider navigation = getProvider(PickBiddingProvider.class);
        if (navigation != null) {
            navigation.startPickNoticeDetailActivity(context, no);
        }
    }

    /**
     * ConcreteDetailActivity2.start(getActivity(), bean.getId(), filterJson);
     */
    public void startConcreteDetail(FragmentActivity activity, String id, MaterialFilterJson filterJson) {
        MerchandiseProvider navigation = getProvider(MerchandiseProvider.class);
        if (navigation != null) {
            navigation.startConcreteDetailActivity2(activity, id, new Gson().toJson(filterJson));
        }
    }

    /**
     * ShopGoodsDetailActivity.start(getContext(), bean.getId(), "", bean.getSkuid());
     */
    public void startShopGoodsDetail(Context context, String id, String s, String skuid) {
        MerchandiseProvider navigation = getProvider(MerchandiseProvider.class);
        if (navigation != null) {
            navigation.startShopGoodsDetailActivity(context, id, s, skuid);
        }
    }

    /**
     * WebsiteInfoActivity.start(context, entity.getCompanyNo(), WebsiteInfoActivity.WEBSITE_FOR_COMPANY);
     */
    public void startWebsiteInfo(Context context, String websiteNo, int websiteType) {
        OtherProvider navigation = getProvider(OtherProvider.class);
        if (navigation != null) {
            navigation.startWebsiteInfoActivity(context, websiteNo, websiteType);
        }
    }

//    /**
//     * EnterpriseAndMapActivity.start(getContext(), longitude, latitude, false);
//     * @param context
//     * @param longitude
//     * @param latitude
//     * @param f
//     */
//    public void startEnterpriseAndMap(Context context, String longitude, String latitude, boolean f) {
//        OtherProvider navigation = getProvider(OtherProvider.class);
//        if (navigation != null) {
//            navigation.startEnterpriseAndMap(context, longitude, latitude,f);
//        }
//    }

    /**
     *   EnterpriseConfigActivity.start(getContext());
     * @param context
     */
//    public void startEnterpriseConfigActivity(Context context) {
//        OtherProvider navigation = getProvider(OtherProvider.class);
//        if (navigation != null) {
//            navigation.startEnterpriseConfigActivity(context);
//        }
//    }
//
//    public void startEnterpriseConfigActivity(Context context, String key) {
//        OtherProvider navigation = getProvider(OtherProvider.class);
//        if (navigation != null) {
//            navigation.startEnterpriseConfigActivity(context);
//        }
//    }

    /**
     * ShopInfoForCompanyTradesActivity.startAct(context, entity.getSupplierId(), entity.getCompanyNo(), 3, 0));
     */
    public void startAct(Context context, String supplierId, String companyNo, int i, int i1) {
        OtherProvider navigation = getProvider(OtherProvider.class);
        if (navigation != null) {
            navigation.startShopInfoForCompanyTradesActivity(context, supplierId, companyNo, i, i1);
        }
    }

    /**
     * VerificationCodeLoginActivity3.start(getActivity(), EventConstant.EVENT_HOME_MEMBER_FRG_JUMP);
     */
    public void startVerificationCodeLogin(Context context, int jump_address) {
        OtherProvider navigation = getProvider(OtherProvider.class);
        if (navigation != null) {
            navigation.startVerificationCodeLoginActivity3(context, jump_address);
        }
    }

    // 跳转个人中心
    public void intentSelfCenter(Fragment parentFragment) {
        /*MainActivity mainActivity = ((HomeFragment3) getParentFragment()).getMainActivity();
        if (mainActivity != null) {
            mainActivity.tabSelfClick(); // // 跳转个人中心
        }*/
        OtherProvider navigation = getProvider(OtherProvider.class);
        if (navigation != null) {
            navigation.jumpSelfCenter(parentFragment);
        }
    }

    /**
     * TeamOfferDetailActivity.start(getActivity(), teamPriceItemEntity.getNo());
     */
    public void startTeamOfferDetail(Activity context, String teamNo) {
        OtherProvider navigation = getProvider(OtherProvider.class);
        if (navigation != null) {
            navigation.startTeamOfferDetailActivity(context, teamNo);
        }
    }

    /**
     * ApprovalManagerActvity.start(MemberRelieveActivity.this, 1);
     */
    public void startApprovalManager(Activity activity, int i) {
        OtherProvider navigation = getProvider(OtherProvider.class);
        if (navigation != null) {
            navigation.startApprovalManagerActvity(activity, i);
        }
    }

    /**
     * NimUIKit.startP2PSession(MemberCompanyWebActivity.this, code.imAccount);
     */
    public void startP2PSession(Activity memberCompanyWebActivity, String imAccount) {
        OtherProvider navigation = getProvider(OtherProvider.class);
        if (navigation != null) {
            navigation.startNimUIKit(memberCompanyWebActivity, imAccount);
        }
    }

    public void startQuotedOwnerActivity(Context activity, String no) {
        OtherProvider navigation = getProvider(OtherProvider.class);
        if (navigation != null) {
            navigation.startQuotedOwnerActivity(activity, no);
        }
    }


    /**
     * 获取当前登录身份的团队名称或者公司No
     */
    public String getTeamOrCompanyNameNo() {
        /*String no = "";
        if (isCompany()) {
            no = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        } else if (getUserInfo() != null && getUserInfo().getTeamRespVO() != null) {
            no = getUserInfo().getTeamRespVO().getNo();
        }*/
        OtherProvider navigation = getProvider(OtherProvider.class);
        if (navigation != null) {
            navigation.getTeamOrCompanyNameNo();
        }
        return "";
    }

    /**
     * 获取当前登录身份的团队名称或者公司名称
     */
    public String getTeamOrCompanyName() {
        /*String name = "";
        if (isCompany()) {
            name = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
        } else if (getUserInfo() != null && getUserInfo().getTeamRespVO() != null) {
            name = getUserInfo().getTeamRespVO().getName();
        }*/
        OtherProvider navigation = getProvider(OtherProvider.class);
        if (navigation != null) {
            navigation.getTeamOrCompanyName();
        }
        return "";
    }

    /**
     * 获取当前用户no
     */
    public String getUserNo() {
        /*String no = "";
        if (getUserInfo() != null) {
            no = getUserInfo().getUserNo();
        }*/
        OtherProvider navigation = getProvider(OtherProvider.class);
        if (navigation != null) {
            navigation.getUserNo();
        }
        return "";
    }

    public void startFreightPrjDetailActivity(Context context, String sourceNo, boolean isOrder, boolean position) {
        OtherProvider navigation = getProvider(OtherProvider.class);
        if (navigation != null) {
            navigation.startFreightPrjDetailActivity(context, sourceNo, isOrder, position);
        }
    }

    public void startGeneralPrjDetailActivity(Context context, String sourceNo, int goodstype, boolean position) {
        OtherProvider navigation = getProvider(OtherProvider.class);
        if (navigation != null) {
            navigation.startGeneralPrjDetailActivity(context, sourceNo, goodstype, position);
        }
    }




    public void getLocalPosition(Context context, SimpleARouteCallback callback) {
        OtherProvider navigation = getProvider(OtherProvider.class);
        if (navigation != null) {
            navigation.getLocalPosition(context, callback);
        }
    }

    // 跳转h5界面
    public void startWebViewX5(Context context, String url) {
        // WebViewX5HostActivity.start(fragment.getActivity(), url);
        WebViewProvider navigation = getProvider(WebViewProvider.class);
        if (navigation != null) {
            navigation.start(context, url);
        }
    }

    // 跳转h5界面
    public void startWebViewX5(Context context, String url,String id,String type,String state) {
        // WebViewX5HostActivity.start(fragment.getActivity(), url);
        WebViewProvider navigation = getProvider(WebViewProvider.class);
        if (navigation != null) {
            navigation.start(context, url,id,type,state);
        }
    }

    public void startWebViewX5(Context context, String url, int code) {
        // WebViewX5HostActivity.start(fragment.getActivity(), url);
        WebViewProvider navigation = getProvider(WebViewProvider.class);
        if (navigation != null) {
            navigation.start(context, url, code);
        }
    }

    public void startWebViewX5(Context context, String url, String id) {
        // WebViewX5HostActivity.start(fragment.getActivity(), url, id);
        WebViewProvider navigation = getProvider(WebViewProvider.class);
        if (navigation != null) {
            navigation.start(context, url, id);
        }
    }
}
